<template>
  <div class="test-content">
    <div class="chatting-context">
      <Card :bordered="false">
        <template #title>
          <Dropdown>
            <div class="dropddown-title">
              文本对话
              <Icon type="ios-arrow-down"></Icon>
            </div>
            <template #list>
              <DropdownMenu>
                <DropdownItem>文本对话</DropdownItem>
              </DropdownMenu>
            </template>
          </Dropdown>
        </template>
        <template #extra>
          <Space>
            <Icon type="ios-information-circle-outline" size="20" />
            <Icon class="back-icon" type="md-refresh" size="20" @click="emit('back')" />
          </Space>
        </template>

        <div ref="conversationRef" class="conversation-body">
          <ul v-if="anwList.length" class="reply">
            <li v-for="(item, index) in anwList" :key="index" :class="{ 'user-answer': item.user }">
              <div class="user-info">
                <template v-if="!item.user">
                  <Icon type="logo-octocat" size="36" />
                  <span class="robot-name">{{ item.nickName }}</span>
                </template>

                <Icon v-else class="user-icon" type="md-person" size="28" />

                <span class="date">{{ item.createtime }}</span>
              </div>
              <div ref="answerRef" class="answer-value">
                <div v-html="item.value"></div>

                <ul class="search-list">
                  <li
                    v-for="(group, key) in item.suggest"
                    :key="key"
                    @click="getAnsData(group.title)"
                  >
                    {{ group.title }}
                  </li>
                </ul>
              </div>
            </li>
          </ul>

          <template v-else>
            <span class="default-label">试试这些例子</span>

            <ul class="default-question">
              <li v-for="(item, index) in defaultAnw" :key="index" @click="getAnsData(item.value)">
                {{ item.value }}
                <a-icon type="arrow-right" class="arrow-right-icon" />
              </li>
            </ul>
          </template>
        </div>

        <div class="search-input">
          <Input
            v-model="searchValue"
            type="textarea"
            maxlength="1000"
            resize="none"
            show-word-limit
            :rows="3"
            placeholder="请输入您想要问的问题"
            @on-enter="getAnsData()"
          />

          <div class="search-btn">
            <!-- <Icon type="md-code" size="20" /> -->
            <Button type="primary" icon="md-paper-plane" :loading="loading" @click="getAnsData()" />
          </div>
        </div>
      </Card>
    </div>

    <div class="history-context">
      <span class="title">召回结果({{ recallList.length }})</span>

      <ul class="history-list">
        <li v-for="item in recallList" :key="item.id">
          <div class="progress-item">
            <span class="name">{{ item.title }}</span>
            <Progress :stroke-width="8" stroke-color="#6360b4" :percent="item.progressValue" />
          </div>

          <p class="desc">{{ item.content }}</p>
          <p class="desc">文档: {{ item.name }}</p>
        </li>

        <p v-if="!recallList.length" class="no-thing">暂无召回信息~</p>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { Message } from 'view-ui-plus'
import moment from 'moment'
import { userStore } from '@/store/userInfo'
import { updateATagTarget } from '@/util'

import createWebSocket from '@/util/websocket'
import { marked } from 'marked'

marked.setOptions({
  sanitize: false, // 关闭sanitize以允许HTML标签通过
  renderer: new marked.Renderer(),
  gfm: true, // 启用GitHub风格的Markdown
  breaks: true, // 允许回车换行
  smartLists: true,
  smartypants: false, // 不转换引号、破折号等
  xhtml: false // 不使用自闭合标签
})
const { userInfo } = userStore()

const props = defineProps({
  knowDetails: Object
})

const loading = ref(false)

const defaultAnw = [
  { value: '如何退出无障碍模式' },
  { value: '复制旧东西' },
  { value: '蓝牙耳机产品名称?' },
  { value: 'oppo平板名称' }
]

const emit = defineEmits(['back'])

const anwList = ref([])

const searchValue = ref('')

const socket = createWebSocket()

socket.on('connect', () => {
  console.log('连接成功')
  // 发送初始化消息
  socket.send('new', {
    // orgi: 'ukewo',
    // appid: '8da803feb3d55ee739d7400ff098256b',
    // aiid: '043710be74784437bb8aa88017af5248',
    // userid: '4028cac3614cd2f901614cf8be1f0324',
    // user: '4028cac3614cd2f901614cf8be1f0324',
    // session: '2f068570bec246c4879dfedaa20a59fc',
    // debug: true,
    // osname: '',
    // browser: ''

    user: userInfo.id,
    orgi: userInfo.orgi,
    session: props.knowDetails.contextid,
    appid: props.knowDetails.appid,
    aiid: props.knowDetails.aihead.id
    // aiid: 'efc3dccab1734ae385a0d9214e5990aa'
  })
})

socket.on('message', (data) => {
  if (data.calltype === 'out') {
    anwList.value.push({
      ...data,
      value: marked(updateATagTarget(data.message))
    })

    nextTick(() => {
      const el = conversationRef.value
      el.scrollTop = el.scrollHeight
    })
  }
})

socket.on('agentstatus', (data) => {
  console.log('agentstatus', data)
})

socket.on('status', (data) => {
  console.log('status', data)
})

//找回结果
const recallList = ref([])
socket.on('doc', (data) => {
  recallList.value = data.map(item=>{
    const similarity = +item.similarity
    return {
      ...item,
      progressValue: similarity.toFixed(2)
    }
  })
})

const getTimeNow = () => {
  return moment().format('YYYY-MM-DD HH:mm:ss')
}

const conversationRef = ref(null)
const getAnsData = (val) => {
  const searchText = val || searchValue.value

  if (!searchText.trim()) {
    return (searchValue.value = '')
  }

  anwList.value.push({
    value: searchText,
    user: true,
    createtime: getTimeNow()
  })

  socket.send({
    // appid: '8da803feb3d55ee739d7400ff098256b',
    // userid: '4028cac3614cd2f901614cf8be1f0324',
    // username: '',
    // channel: 'webim',
    // debug: true,
    // type: 'message',
    // contextid: '486b1e7469064f51a88e5f5e335f21ff',
    // orgi: 'ukewo',
    appid: props.knowDetails.appid,
    userid: userInfo.id,
    username: userInfo.username,
    channel: 'webim',
    debug: true,
    type: 'message',
    contextid: props.knowDetails.contextid,
    orgi: userInfo.orgi,
    // mediaid: '754d136820f640c1b8c414b5c4826b72',
    message: searchText
  })

  searchValue.value = ''
}

onMounted(() => {})

onBeforeUnmount(() => {
  socket.destory()
})
</script>

<style scoped lang="scss">
.test-content {
  display: flex;
  height: calc(100% - 50px);
  .chatting-context {
    flex: 1;
    margin-right: 10px;
    background-color: #f3f4f7;
    min-width: 400px;
    .ivu-card {
      width: 100%;
      // height: 100%;
      border-radius: 0;
      &:hover {
        box-shadow: unset;
      }
      :deep(.ivu-card-body) {
        background-color: #f3f4f7;
        padding: 20px 0 0;
        .search-input {
          position: relative;
          margin-top: 16px;
          .ivu-input-type-textarea {
            .ivu-input {
              resize: none;
              padding-right: 40px;
            }
            .ivu-input-word-count {
              right: 52px;
            }
          }
          .search-btn {
            position: absolute;
            right: 6px;
            bottom: 4px;
            display: flex;
            flex-direction: column;
            .ivu-btn {
              width: 40px;
              height: 32px;
              line-height: 0;
            }
            .ivu-icon-md-code {
              transform: rotate(-45deg);
              margin-bottom: 15px;
              margin-left: 15px;
            }
          }
        }
      }
    }
    .back-icon {
      cursor: pointer;
    }
  }
  .history-context {
    width: 320px;
    min-width: 320px;
    background-color: #fff;
    padding: 12px;
    .title {
      color: #17233d;
      font-size: 16px;
      font-weight: bold;
    }

    .history-list {
      margin-top: 16px;
      height: calc(100% - 34px);
      overflow-y: auto;
      margin-right: -12px;
      padding-right: 12px;
      position: relative;
      > li {
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 12px;
        &:nth-child(n + 2) {
          margin-top: 16px;
        }
        .progress-item {
          display: flex;
          .name {
            width: 50px;
          }
          :deep(.ivu-progress) {
            flex: 1;
            .ivu-progress-outer {
              padding-right: 80px;
              margin-right: -80px;
            }
            .ivu-progress-text-inner {
              &::before {
                content: '相似值: ';
              }
            }
          }
        }
        .desc {
          color: #666;
          margin-top: 8px;
        }
      }

      .no-thing {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 14px;
        color: #999;
      }
    }
  }
}

.conversation-body {
  padding: 0 20px;
  // padding: 20px 25%;
  // width: 800px;
  min-width: 200px;
  // max-width: 800px;
  height: calc(100vh - 307px);
  // margin: 16px auto;
  overflow-y: auto;
  .reply {
    > li {
      text-align: left;
      &:nth-child(n + 2) {
        margin-top: 24px;
      }
      &.user-answer {
        text-align: right;
        .user-info {
          flex-direction: row-reverse;
          .user-icon {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background-color: #0066ff;
            text-align: center;
            line-height: 36px;
            color: #fff;
            margin: 0 0 0 8px;
          }
        }
        .answer-value {
          // background-color: #0066ff;
          padding: 6px 12px;
          border-radius: 4px;
          // color: #fff;
          text-align: left;
          margin: -8px 44px 0 0;
        }
      }
      .user-info {
        display: flex;
        .robot-name {
          margin-right: 4px;
          color: #0066ff;
        }
        .ivu-icon {
          margin-right: 8px;
        }
        .date {
          color: #666;
        }
      }
      .answer-value {
        max-width: 80%;
        display: inline-block;
        color: #545658;
        font-size: 16px;
        background-color: #fff;
        border-radius: 4px;
        padding: 6px 12px;
        margin: -8px 0 0 44px;
        .search-list {
          li {
            color: #0066ff;
            cursor: pointer;
            margin-top: 8px;
            &:hover {
              opacity: 0.9;
            }
          }
        }
      }
      .unfold {
        color: #168fff;
        cursor: pointer;
        font-size: 14px;
        &:hover {
          opacity: 0.9;
        }
      }
    }
  }
  .default-label {
    color: #7e8088;
  }
  .default-question {
    display: flex;
    flex-wrap: wrap;
    li {
      margin: 16px 16px 0 0;
      border: 1px solid #e2e7ed;
      border-radius: 4px;
      padding: 4px 8px;
      color: #545658;
      cursor: pointer;
      background-color: #f8f8f8;
      &:hover {
        opacity: 0.9;
      }
      .arrow-right-icon {
        margin-left: 8px;
        font-size: 12px;
        transform: translateY(-1px);
      }
    }
  }
}
</style>
